package top.lingchen.spring5;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @Author 凌宸
 * @create 2021-11-29 下午 10:12
 * @Description
 * @Version 1.0
 */
public class JDKProxy {
    public static void main(String[] args) {
        // 创建接口类的代理对象
        UserDaoImpl userDao = new UserDaoImpl();
        Class[] interfaces = {UserDao.class};
        UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int res = dao.add(1, 2);
        System.out.println("res = " + res);
        /**
         * 方法执行之前...add：传递的参数...[1, 2]
         * 方法之后执行...top.lingchen.spring5.UserDaoImpl@6f94fa3e
         * res = 3
         */
    }
}

class UserDaoProxy implements InvocationHandler{
    // 创建的是谁的代理对象，把谁传递过来
    private Object obj;
    public UserDaoProxy(Object obj){
        this.obj = obj;
    }
    // 增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 方法之前
        System.out.println("方法执行之前..." + method.getName() + "：传递的参数..." + Arrays.toString(args));

        // 被增强的方法执行
        Object res = method.invoke(obj, args);
        // 方法之后
        System.out.println("方法之后执行..." + obj);
        return res;
    }
}
